package com.artmall.manager.common.shiro;

import com.artmall.common.utils.Constant;
import com.artmall.manager.common.utils.ShiroUtils;
import com.artmall.manager.sys.dao.SysMenuMapper;
import com.artmall.manager.sys.dao.SysUserMapper;
import com.artmall.manager.sys.pojo.SysMenu;
import com.artmall.manager.sys.pojo.SysUser;
import com.artmall.manager.sys.service.SysMenuService;
import com.artmall.manager.sys.service.SysUserService;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authc.credential.CredentialsMatcher;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

import java.util.*;

/**
 * @Description:
 * @Author: MING
 * @Eamil lmm_work@163.com
 * @Date: 2018/12/7 15:22
 */
@Component
public class UserRealm extends AuthorizingRealm {

    @Autowired
    SysUserService sysUserService;


    @Autowired
    SysMenuService sysMenuService;

    /**
     *  授权 (验证权限时调用)
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {

        SysUser sysUser = (SysUser) principalCollection.getPrimaryPrincipal();
        Long userId = sysUser.getUserId();

        List<String> permsList;
        // 系统管理员 拥有最高权限
        if(userId == Constant.SUPER_ADMIN){

            List<SysMenu> menuList = sysMenuService.selectList(null);
            permsList =  new ArrayList<>(menuList.size());
            for (SysMenu menu : menuList){
                // 添加所有权限
                permsList.add(menu.getPerms());
            }
        }else {
            permsList = sysUserService.queryAllPerms(userId);
        }

        // 用户权限列表
        Set<String> permsSet = new HashSet<>();
        for (String perms : permsList){
            if (StringUtils.isBlank(perms)){
                continue;
            }
            permsSet.addAll(Arrays.asList(perms.trim().split(",")));
        }

        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.setStringPermissions(permsSet);
        return info;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {

        UsernamePasswordToken token = (UsernamePasswordToken)authenticationToken;
        //查询用户信息
        SysUser sysUser = new SysUser();
        sysUser.setUsername(token.getUsername());
        sysUser = sysUserService.selectOne(sysUser);

        //账号不存在
        if(sysUser == null){
            throw new UnknownAccountException("账号或密码不正确");
        }
        //账号锁定
        if(sysUser.getStatus() == 0){
            throw new LockedAccountException("账号已被锁定,请联系管理员");
        }
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(sysUser, sysUser.getPassword(), ByteSource.Util.bytes(sysUser.getSalt()), getName());

        return info;
    }

    @Override
    public void setCredentialsMatcher(CredentialsMatcher credentialsMatcher) {
        HashedCredentialsMatcher shaCredentialsMatcher = new HashedCredentialsMatcher();
        shaCredentialsMatcher.setHashAlgorithmName(ShiroUtils.hashAlgorithmName);
        shaCredentialsMatcher.setHashIterations(ShiroUtils.hashIterations);
        super.setCredentialsMatcher(shaCredentialsMatcher);
    }
}
